import Sortable from 'sortablejs';
import { reactive, toRefs } from 'vue';
import { TableSortProps } from './types';

export default () => {
  const state = reactive<TableSortProps>({
    sortIndex: [undefined, undefined],
    shouldSort: false,
  });

  const setShouldSort = (shouldSort: TableSortProps['shouldSort']) => {
    state.shouldSort = shouldSort;
  };

  const initSortable = () => {
    const mytb: any = document.querySelector('#mytb tbody');
    Sortable.create(mytb, {
      handle: '.anticon-align-left',
      animation: 150,
      sort: true,
      ghostClass: 'blue-background-class',
      onEnd(event) {
        state.sortIndex[0] = event.oldIndex;
        state.sortIndex[1] = event.newIndex;
      },
    });
  };

  return { ...toRefs(state), initSortable, setShouldSort };
};
